"""
配置管理模块

负责加载和管理程序的配置参数，包括：
1. 几何参数
2. 物理参数
3. 数值计算参数
4. 子通道类型和几何特征
"""

import json
import os
from typing import Dict, Any

class ConfigManager:
    def __init__(self, config_path: str):
        """
        初始化配置管理器
        
        参数:
            config_path (str): 配置文件路径
        """
        self.config_path = config_path
        self.config = self._load_config()
        
    def _load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        
        返回:
            Dict[str, Any]: 配置参数字典
        """
        if not os.path.exists(self.config_path):
            raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
            
        try:
            with open(self.config_path, 'r') as f:
                config = json.load(f)
            return config
        except json.JSONDecodeError as e:
            raise ValueError(f"配置文件格式错误: {str(e)}")
            
    def get_geometry_params(self) -> Dict[str, Any]:
        """获取几何参数"""
        return self.config.get('geometry', {})
        
    def get_physics_params(self) -> Dict[str, Any]:
        """获取物理参数"""
        return self.config.get('physics', {})
        
    def get_numerical_params(self) -> Dict[str, Any]:
        """获取数值计算参数"""
        return self.config.get('numerical', {})
        
    def get_channel_types(self) -> Dict[str, str]:
        """获取子通道类型定义"""
        return self.config.get('channel_types', {})
        
    def get_channel_geometry(self) -> Dict[str, Dict[str, float]]:
        """获取子通道几何特征"""
        return self.config.get('channel_geometry', {})
        
    def validate_config(self) -> bool:
        """
        验证配置参数的完整性和有效性
        
        返回:
            bool: 配置是否有效
        """
        required_sections = ['geometry', 'physics', 'numerical', 
                           'channel_types', 'channel_geometry']
        
        # 检查必需的配置部分是否存在
        for section in required_sections:
            if section not in self.config:
                raise ValueError(f"缺少必需的配置部分: {section}")
        
        # 验证几何参数
        geometry = self.get_geometry_params()
        required_geometry = ['n_axial', 'n_channels', 'channel_length', 
                           'rod_diameter', 'rod_pitch', 'bundle_size']
        for param in required_geometry:
            if param not in geometry:
                raise ValueError(f"缺少几何参数: {param}")
                
        # 验证物理参数
        physics = self.get_physics_params()
        required_physics = ['inlet_pressure', 'inlet_temperature', 
                          'inlet_mass_flux', 'outlet_pressure', 'average_heat_flux']
        for param in required_physics:
            if param not in physics:
                raise ValueError(f"缺少物理参数: {param}")
                
        # 验证数值参数
        numerical = self.get_numerical_params()
        required_numerical = ['dt', 'max_iterations', 
                            'convergence_criteria', 'save_interval']
        for param in required_numerical:
            if param not in numerical:
                raise ValueError(f"缺少数值参数: {param}")
        
        return True
        
    def update_config(self, section: str, key: str, value: Any) -> None:
        """
        更新配置参数
        
        参数:
            section (str): 配置部分名称
            key (str): 参数名
            value (Any): 参数值
        """
        if section not in self.config:
            raise ValueError(f"配置部分不存在: {section}")
            
        self.config[section][key] = value
        
    def save_config(self) -> None:
        """保存配置到文件"""
        with open(self.config_path, 'w') as f:
            json.dump(self.config, f, indent=4) 